package org.hyl.javabase.多线程;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class caiDemo {
	private static List<菜> cas = new ArrayList<>();

	public static void main(String[] arg) {
		fun1();

	}

	public static void fun1() {

		for (int i = 0; i < 10; i++) {
			cas.add(new 菜(i + 1));
		}
		List<助理> zl = new ArrayList<助理>();

		zl.add(new 助理("洗菜工1", "洗菜"));// 9
		zl.add(new 助理("洗菜工2", "洗菜"));
		zl.add(new 助理("洗菜工3", "洗菜"));
		zl.add(new 助理("切菜工4", "切菜"));
		zl.add(new 助理("切菜工5", "切菜"));
		zl.add(new 助理("切菜工6", "切菜"));
		zl.add(new 助理("炒菜工7", "炒菜"));
		zl.add(new 助理("炒菜工8", "炒菜"));
		zl.add(new 助理("炒菜工9", "炒菜"));

		for (助理 z : zl) {
			z.setCais(cas);
			new Thread(z).start();
		}
	}
}

class 菜 {
	private int state = 0; // 0 未洗过,1表示洗过了,2表示切过了,3表示炒过了
	public String name = "菜";

	public 菜(int i) {
		this.name += i;
	}

	public synchronized int getState() {
		return state;
	}

	public synchronized void setState(int state) {
		this.state = state;
	}

}

class 助理 implements Runnable { // implements 洗菜工, 切菜工, 炒菜工
	String name = "";
	boolean state = false;// false 空闲 ；true 繁忙
	List<菜> caiList;
	int job = 0;
	String jobname = "";

	public 助理(String name, String job) {
		this.name = name;
		this.jobname = job;
		this.job = (job.equals("洗菜")) ? 1 : (job.equals("切菜")) ? 2 : (job.equals("炒菜")) ? 3 : 0;
	}

	public void setCais(List<菜> cais) {
		caiList = cais;
	}

	public void run() {
		// TODO Auto-generated method stub

		if (caiList == null)
			return;

		while (isNoFinish()) {

			if (this.state)
				continue;
			else
				work(job);

		}

	}

	public boolean isNoFinish() {
		for (菜 c : caiList) {
			if (c.getState() == (job-1))
				return true;
		}
		return false;
	}



	public void work(int job) {
		String s="";		
		for (菜 cai : caiList) {
			synchronized (cai) {
				if (cai.getState() == (job-1)) {
					state = true;
					System.out.println(name + "在"+jobname+"(" + cai.name + ") state="+cai.getState());
					// Thread.sleep(30);
					cai.setState(job);
					state = false;
				}
			}
		}

	}


}
